import router from './router'
import store from './store'

import NProgress from 'nprogress' // progress bar
// 注意引入样式
import 'nprogress/nprogress.css' // progress bar style

const whiteList = ['/login', '/work', '/404'] // no redirect whitelist

// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  // start progress bar
  // 开启进度条
  NProgress.start()
  // determine whether the user has logged in
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        await store.dispatch('user/getUserInfoAction')
      }
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next('/login')
      NProgress.done()
    }
  }
})

// 路由后置守卫
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
